#include "rect_list.h"
#include "stdlib.h"
#include "stdio.h"

static int rectlist_counter=0;
/** @brief RectList constructor
 * @param Rect *r
 * @param RectList *next
 * @param HWND hWnd
 * @note
 */
RectList::RectList(Rect *r, RectList *next, HWND hWnd)
{
    this->rect =r;
    this->next =next;
    this->prev =0;
    this->hWnd =hWnd;
}
/** @brief RectList constructor
 * @param Rect *r
 * @note
 */
RectList::RectList(Rect *r)
{
    this->rect =r;
    prev=next =0;
}
/** @brief RectList destructor
 * @note
 */
RectList::~RectList()
{
}

/** @brief operator 'delete' definitions  
 * @note
 */    
void RectList::operator delete(void *t)
{
#ifdef DEBUG_DC
    printf("        List counter %d, freeing %x \n", rectlist_counter--, t );
#endif
    port_free(t);
}
/** @brief operator 'new' definitions  
 * @note
 */ 
void *RectList::operator new(unsigned int len)
{
    void *t;
    t= port_malloc(len);
#ifdef DEBUG_DC
    printf("\n         List counter %d, malloced %x\n", ++rectlist_counter, t);
#endif
    return t;
}

/** @brief find a rectangular
 * @param Rect *r
 * @return RectList*
 * @note
 */ 
RectList* RectList::findRect(Rect *r)
{
    RectList *p;
    for(p=this; p; p=p->next)
    {
        if(p->rect ==r) return p;
    }

    return 0;
}

/** @brief add a rectangular
 * @param Rect *r
 * @param HWND hWnd
 * @return RectList*
 * @note
 */
RectList* RectList::addRect(Rect *r, HWND hWnd)
{
    RectList *p;

    p =new RectList(r, this, hWnd);
    return p;
}

/** @brief remove a rectangular
 * @param Rect *r
 * @return RectList*
 * @note
 */
RectList* RectList::removeRect(Rect *r)
{
    RectList *p;
    RectList *t;

    //item on header
    if(this->rect ==r)
    {
        p =this->next;
        delete this;

        return p;
    }

    //item not on header
    for(p=this; p && p->next; )
    {
        if(p->next->rect ==r)
        {
            t =p->next;
            p->next =p->next->next;
            delete t;

            return this;
        }
        else
        {
            p =p->next;
        }
    }
    
    return this;
}

